<template>
  <view class="page">
    <!-- 顶部统计卡片 -->
    <view class="stats-card">
      <view class="stat-item">
        <text class="stat-label">商品总数</text>
        <text class="stat-value">{{ stats.total }}</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">已上架</text>
        <text class="stat-value active">{{ stats.onSale }}</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">已下架</text>
        <text class="stat-value">{{ stats.offSale }}</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">库存预警</text>
        <text class="stat-value warning">{{ stats.lowStock }}</text>
      </view>
    </view>

    <!-- Tab切换 -->
    <view class="tabs">
      <view 
        class="tab-item" 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="{ active: activeTab === index }"
        @click="switchTab(index)"
      >
        <text class="tab-text">{{ tab }}</text>
      </view>
    </view>

    <view class="search-box">
      <input class="search-input" v-model="keyword" placeholder="搜索商品名称/描述" confirm-type="search" @confirm="onSearch" />
      <view class="btn-search" @click="onSearch">搜索</view>
    </view>

    <!-- 商品列表 -->
    <scroll-view class="product-list" scroll-y lower-threshold="60" @scrolltolower="loadMore">
      <view class="product-item" v-for="product in productList" :key="product.id">
        <image 
          class="product-image" 
          :src="product.image || '/static/images/product-default.png'"
          mode="aspectFill"
        ></image>
        
        <view class="product-info">
          <view class="product-header">
            <text class="product-name">{{ product.name }}</text>
            <view class="product-status" :class="{ 'status-on': product.status === 1 }">
              {{ product.status === 1 ? '已上架' : '已下架' }}
            </view>
          </view>
          
          <view class="product-detail">
            <text class="product-price">¥{{ product.price }}</text>
            <text class="product-stock">库存: {{ product.stock }}</text>
            <text class="product-sales">销量: {{ product.sales }}</text>
          </view>
          
          <view class="product-actions">
            <view class="btn-action" @click="editProduct(product)">
              <text class="action-icon">✏️</text>
              <text class="action-text">编辑</text>
            </view>
            <view 
              class="btn-action" 
              @click="toggleStatus(product)"
            >
              <text class="action-icon">{{ product.status === 1 ? '📉' : '📈' }}</text>
              <text class="action-text">{{ product.status === 1 ? '下架' : '上架' }}</text>
            </view>
            <view class="btn-action danger" @click="deleteProduct(product)">
              <text class="action-icon">🗑️</text>
              <text class="action-text">删除</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty" v-if="productList.length === 0 && !loading">
        <text class="empty-icon">📦</text>
        <text class="empty-text">暂无商品</text>
        <view class="btn-add-first" @click="addProduct">
          <text>添加第一个商品</text>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="loadmore" v-if="productList.length > 0">
        <text class="loadmore-text">{{ loadingText }}</text>
      </view>
    </scroll-view>

    <!-- 添加商品按钮 -->
    <view class="btn-add-float" @click="addProduct">
      <text class="add-icon">+</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tabs: ['全部', '已上架', '已下架', '库存预警'],
      activeTab: 0,
      productList: [],
      keyword: '',
      stats: {
        total: 0,
        onSale: 0,
        offSale: 0,
        lowStock: 0
      },
      page: 1,
      pageSize: 10,
      loading: false,
      finished: false
    }
  },
  computed: {
    loadingText() {
      if (this.loading) return '加载中...'
      if (this.finished) return '没有更多了'
      return '上拉加载更多'
    }
  },
  onLoad() {
    this.loadStats()
    this.loadProducts()
  },
  onShow() {
    // 从编辑页返回时刷新列表
    if (this.$mp && this.$mp.page && this.$mp.page.$vm.needRefresh) {
      this.page = 1
      this.finished = false
      this.loadStats()
      this.loadProducts()
      this.$mp.page.$vm.needRefresh = false
    }
  },
  onPullDownRefresh() {
    this.page = 1
    this.finished = false
    this.loadStats()
    this.loadProducts()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 1000)
  },
  methods: {
    async loadStats() {
      try {
        const { getProductStats } = require('@/api/stats')
        const data = await getProductStats({ stockThreshold: 10 })
        this.stats = {
          total: Number(data?.total || 0),
          onSale: Number(data?.onSale || 0),
          offSale: Number(data?.offSale || 0),
          lowStock: Number(data?.lowStock || 0)
        }
      } catch (error) {
        console.error('加载统计失败:', error)
        this.stats = { total: 0, onSale: 0, offSale: 0, lowStock: 0 }
      }
    },
    
    switchTab(index) {
      this.activeTab = index
      this.page = 1
      this.finished = false
      this.productList = []
      this.loadProducts()
    },
    
    onSearch() {
      this.page = 1
      this.finished = false
      this.productList = []
      this.loadProducts()
    },
    
    async loadProducts() {
      if (this.loading || this.finished) return
      
      this.loading = true
      
      try {
        const { getProductPage } = require('@/api/product')
        
        // 根据tab确定查询条件
        const params = {
          current: this.page,
          size: this.pageSize
        }
        
        // 根据activeTab设置状态筛选
        if (this.activeTab === 1) {
          params.status = 1 // 已上架
        } else if (this.activeTab === 2) {
          params.status = 0 // 已下架
        } else if (this.activeTab === 3) {
          // 库存预警
          params.lowStock = true
        }
        
        if (this.keyword && this.keyword.trim()) {
          params.keyword = this.keyword.trim()
        }
        // 全部商品不传status参数，后端会查询所有状态
        
        const pageData = await getProductPage(params)
        
        //console.log('商品分页数据:', pageData)
        
        const records = pageData.records || []
        
        if (this.page === 1) {
          this.productList = records
        } else {
          this.productList.push(...records)
        }
        
        this.loading = false
        
        if (records.length < this.pageSize || this.page >= (pageData.pages || 1)) {
          this.finished = true
        }
      } catch (error) {
        console.error('加载商品失败:', error)
        this.loading = false
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    },
    
    loadMore() {
      if (this.loading || this.finished) return
      this.page++
      this.loadProducts()
    },
    
    addProduct() {
      uni.navigateTo({
        url: '/pages/merchant/product-edit'
      })
    },
    
    editProduct(product) {
      uni.navigateTo({
        url: '/pages/merchant/product-edit?id=' + product.id
      })
    },
    
    async toggleStatus(product) {
      const action = product.status === 1 ? '下架' : '上架'
      
      uni.showModal({
        title: '提示',
        content: `确定要${action}该商品吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '处理中...' })
              
              // TODO: 调用上下架API
              const { updateProductStatus } = require('@/api/product')
              await updateProductStatus(product.id, product.status === 1 ? 0 : 1)
              
              uni.hideLoading()
              uni.showToast({
                title: `${action}成功`,
                icon: 'success'
              })
              
              // 刷新列表
              this.page = 1
              this.finished = false
              this.productList = []
              this.loadStats()
              this.loadProducts()
            } catch (error) {
              console.error(`${action}商品失败:`, error)
              uni.hideLoading()
              uni.showToast({
                title: error.message || `${action}失败`,
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    deleteProduct(product) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该商品吗？删除后不可恢复',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '删除中...' })
              
              const { deleteProduct } = require('@/api/product')
              await deleteProduct(product.id)
              
              uni.hideLoading()
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
              
              // 刷新列表
              this.page = 1
              this.finished = false
              this.productList = []
              this.loadStats()
              this.loadProducts()
            } catch (error) {
              console.error('删除商品失败:', error)
              uni.hideLoading()
              uni.showToast({
                title: error.message || '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  height: 100vh;
  overflow: hidden;
  background: #f5f7fa;
  padding-bottom: 160rpx;
  display: flex;
  flex-direction: column;
}

/* 统计卡片 */
.stats-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 32rpx 24rpx;
  display: flex;
  justify-content: space-around;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12rpx;
  
  .stat-label {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.8);
  }
  
  .stat-value {
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
    
    &.active {
      color: #51cf66;
    }
    
    &.warning {
      color: #ffa500;
    }
  }
}

/* Tab栏 */
.tabs {
  background: #fff;
  display: flex;
  padding: 0 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.search-box {
  display: flex;
  gap: 16rpx;
  padding: 20rpx;
  background: #fff;
}

.search-input {
  flex: 1;
  height: 72rpx;
  padding: 0 24rpx;
  border-radius: 36rpx;
  background: #f5f7fa;
  font-size: 26rpx;
}

.btn-search {
  width: 140rpx;
  height: 72rpx;
  border-radius: 36rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
}

.tab-item {
  flex: 1;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  
  .tab-text {
    font-size: 28rpx;
    color: #666;
    transition: all 0.3s;
  }
  
  &.active {
    .tab-text {
      color: #667eea;
      font-weight: bold;
    }
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 40rpx;
      height: 6rpx;
      background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
      border-radius: 3rpx;
    }
  }
}

/* 商品列表 */
.product-list {
  flex: 1;
  height: 0;
  padding: 20rpx;
}

.product-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  display: flex;
  gap: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  flex-shrink: 0;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12rpx;
}

.product-name {
  flex: 1;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.product-status {
  background: #f5f5f5;
  color: #999;
  font-size: 22rpx;
  padding: 6rpx 12rpx;
  border-radius: 8rpx;
  white-space: nowrap;
  
  &.status-on {
    background: #e7f5ff;
    color: #1890ff;
  }
}

.product-detail {
  display: flex;
  gap: 24rpx;
  font-size: 24rpx;
  color: #666;
}

.product-price {
  font-size: 32rpx;
  color: #ff4d4f;
  font-weight: bold;
}

.product-actions {
  display: flex;
  gap: 16rpx;
}

.btn-action {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 16rpx 8rpx;
  background: #f5f7fa;
  border-radius: 8rpx;
  
  &.danger {
    background: #fff1f0;
    color: #ff4d4f;
  }
  
  .action-icon {
    font-size: 28rpx;
  }
  
  .action-text {
    font-size: 24rpx;
    color: #666;
  }
  
  &.danger .action-text {
    color: #ff4d4f;
  }
}

/* 空状态 */
.empty {
  padding: 120rpx 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 32rpx;
  
  .empty-icon {
    font-size: 160rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
  
  .btn-add-first {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    font-size: 28rpx;
    padding: 20rpx 48rpx;
    border-radius: 40rpx;
  }
}

/* 加载更多 */
.loadmore {
  padding: 40rpx 20rpx;
  text-align: center;
  
  .loadmore-text {
    font-size: 24rpx;
    color: #999;
  }
}

/* 悬浮添加按钮 */
.btn-add-float {
  position: fixed;
  right: 40rpx;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
  z-index: 100;
  
  .add-icon {
    font-size: 64rpx;
    color: #fff;
    font-weight: 300;
  }
}
</style>

